/* symtab.c
 *
 * Implements the symbol table
 *
 * A flat symbol table is the root of all evil.
 */

#include "symtab.h"



/* ------------------------------------------------------------
 * Initializes the symbol table
 * ------------------------------------------------------------
 */

void cfg_symtab_reinit_mark()
{
	struct cfg_symtab_elem *temp = cfg_symtab;
	while (temp != NULL)
	{
		temp->marked = 0;
		temp = temp->next;
	}
}

int cfg_symtab_is_userdef(int key)
{
        struct cfg_symtab_elem *elem = cfg_symtab_lookup(key);
        if (elem->type == SYM_TYPE_USER) return 1;
        else return 0;
}

void cfg_symtab_init()
{
	if (cfg_symtab)
		free(cfg_symtab);
       
//        cfg_symtab = NULL;

	cfg_symtab = (struct cfg_symtab_elem *)(malloc(sizeof(struct cfg_symtab_elem)));
        cfg_symtab->key = 0;
        cfg_symtab->next = NULL;
}

void cfg_symtab_add (int type, int key, char *val)
{
	struct cfg_symtab_elem *temp = cfg_symtab;
	//if (cfg_symtab == NULL)
	//	cfg_symtab = node;
	//else
	//{
		/* add the node to cfg_symtab */
		while (temp->next != NULL)
		{
			if (temp->key == key) return;
			temp = temp->next;
		}
	struct cfg_symtab_elem * node = (struct cfg_symtab_elem *)(malloc(sizeof(struct cfg_symtab_elem)));

	/* Update the node */
	node->key = key;
	node->val = (char *)(malloc(strlen(val)*sizeof(char)));
	strcpy(node->val, val);
	node->type = type;
	node->next = NULL;

		temp->next = node;
	//}
}

void cfg_symtab_print()
{
	struct cfg_symtab_elem *temp = cfg_symtab;
	/* loop the nodes to cfg_symtab */
	printf("******************SYMTAB**************************\n");
	while (temp != NULL)
	{
		printf("Key:%d\tVal:%s\tType:%d\n", temp->key, temp->val, temp->type);
		temp = temp->next;
	}
	printf("******************SYMTAB END**********************\n");
}

struct cfg_symtab_elem * cfg_symtab_lookup(int key)
{
	struct cfg_symtab_elem *temp = cfg_symtab;
	/* loop the nodes to cfg_symtab */
	while (temp != NULL)
	{
		if (temp->key == key)
		{
			return temp;
		}

		temp = temp->next;
	}
	return NULL;
}

char * cfg_symtab_get_val(int key)
{
	struct cfg_symtab_elem *temp = cfg_symtab;
	/* loop the nodes to cfg_symtab */
	while (temp != NULL)
	{
		if (temp->key == key)
		{
			return temp->val;
		}

		temp = temp->next;
	}
	return inttostring(key);
}

void cfg_symtab_remove_key(int key)
{
	struct cfg_symtab_elem *temp = cfg_symtab;
	struct cfg_symtab_elem *toDel = NULL;

	while (temp != NULL && toDel == NULL)
	{
		if (temp->next != NULL && temp->next->key == key) {
			toDel = temp->next;
			temp->next = temp->next->next;
		}
		else if (temp->key == key) 
		{
			cfg_symtab = temp->next;
			toDel = temp;
		}
		temp = temp->next;
	}

	if (toDel != NULL) {
		free(toDel);
	}

}

void symtab_init()
{


}



/* ------------------------------------------------------------
 * Prints the contents of the symbol table
 * ------------------------------------------------------------
 */
void symtab_print(int numOfTabs)
{


}

